package com.utome.weekendproject.service.securityService;

import com.utome.weekendproject.Constant;
import com.utome.weekendproject.utils.SnowflakeIdWorker;
import com.utome.weekendproject.javabeans.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class LoginServiceImpl implements UserDetailsService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        ValueOperations<String, SysUser> valueOperations = redisTemplate.opsForValue();
        SysUser sysUser = valueOperations.get(Constant.USER_KEY + s);
        List<GrantedAuthority> grantedAuthorities = new ArrayList();
        User user = new User(sysUser.getMobileNo(), sysUser.getPassword(), grantedAuthorities);
        return user;
    }

    public SysUser register(SysUser sysUser) {
        sysUser.setId(SnowflakeIdWorker.getId());
        ValueOperations<String, SysUser> valueOperations = redisTemplate.opsForValue();
        String key = Constant.USER_KEY + sysUser.getMobileNo();
        valueOperations.set(key, sysUser);
        return valueOperations.get(key);
    }
}
